package mmc;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import org.lwjgl.LWJGLException;

@SuppressWarnings("serial")
public class Launcher extends JFrame implements ActionListener{

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length==2)
			new Launcher(args[0],args[1],4711);
		else if(args.length==3)
			new Launcher(args[0],args[1],new Integer(args[2]));
		else
			new Launcher();
			//System.out.println("usage: mmcid <loginName> <host> [port]");
		
	}
	
	
	public Launcher()
	{
		this("", "", 0);
	}
	
	public JTextField t_host, t_port, t_name;
	public JLabel l_status;
	
	public Launcher(String name, String host, Integer port)
	{
		//System.out.println(port);
		this.setVisible(true); //.show();
		this.setPreferredSize(new Dimension(300, 200));
		
		GridLayout grid = new GridLayout(5,2);		
		this.setLayout(grid);
		
		JLabel l_host = new JLabel("Host-IP:");		
		this.add(l_host);
		
		t_host = new JTextField(host);
		this.add(t_host);
		
		JLabel l_port = new JLabel("Port:");		
		this.add(l_port);
		
		t_port = new JTextField(port+"");
		this.add(t_port);
		
		JLabel l_name = new JLabel("Login-Name:");		
		this.add(l_name);
		
		t_name = new JTextField(name);
		this.add(t_name);
		
		
		JButton b_ok = new JButton("Connect");
		this.add(b_ok);
		
		b_ok.addActionListener(this);
		
		JButton b_exit = new JButton("Exit");
		this.add(b_exit);
		
		b_exit.addActionListener(new ActionListener() {			
			@Override
			public void actionPerformed(ActionEvent e) {				
				System.exit(0);
			}
		});
		
		l_status = new JLabel();
		
		this.add(l_status);
		
		this.pack();
	}
	
	public void actionPerformed(ActionEvent e) {
		try {
			try {
				String host = t_host.getText();
				int port = new Integer(t_port.getText());
				final Socket socket = new Socket(host, port);
				
				this.dispose();
				
				new Thread(new Runnable(){public void run(){try {
					new Client(t_name.getText(), socket);
				} catch (LWJGLException e) {
					e.printStackTrace();
				}}}).start();
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e1) {
			l_status.setText("Could not connect to server");
			//throw new RuntimeException("Coult not connect to server: "+e1.getMessage(),e1);			
		}				
	}
	   
}
